package com.kun.base.util

import android.app.Application
import android.os.Parcelable
import com.google.gson.Gson
import com.tencent.mmkv.MMKV

/**
 * @author: Administrator
 * Created by Android Studio.
 * Date: 2020/9/1
 * Time: 13:44
 */
object MMKVUtils {
    private lateinit var mmkv: MMKV
    fun initMMKV(application: Application?) {
        MMKV.initialize(application)
        mmkv = MMKV.defaultMMKV()
    }

    /**
     * 存值
     *
     * @param key   key
     * @param value value
     */
    fun put(key: String?, value: Any?) {
        if (value is Int) {
            mmkv.encode(key, value)
        } else if (value is Float) {
            mmkv.encode(key, value)
        } else if (value is Long) {
            mmkv.encode(key, value)
        } else if (value is Double) {
            mmkv.encode(key, value)
        } else if (value is Boolean) {
            mmkv.encode(key, value)
        } else if (value is String) {
            mmkv.encode(key, value)
        } else if (value is Parcelable) {
            mmkv.encode(key, value)
        } else {
            mmkv.encode(key, Gson().toJson(value))
        }
    }

    /**
     * 取值
     *
     * @param key               key
     * @param value             value
     * @return
     */
    operator fun get(key: String?, value: Any?): Any? {
        if (value is Int) {
            return mmkv.decodeInt(key, value)
        } else if (value is Float) {
            return mmkv.decodeFloat(key, value)
        } else if (value is Long) {
            return mmkv.decodeLong(key, value)
        } else if (value is Double) {
            return mmkv.decodeDouble(key, value)
        } else if (value is Boolean) {
            return mmkv.decodeBool(key, value)
        } else if (value is String) {
            return mmkv.decodeString(key, value)
        } else if (value is Parcelable) {
            return mmkv.decodeParcelable(
                key,
                value.javaClass,
                value
            )
        } else if (value != null) {
            val str: String = mmkv.decodeString(key, "")
            LogUtils.e("cookies: "+str)
            if ("" != str) {
                return Gson().fromJson(str, value.javaClass)
            }
        }
        return value
    }

    fun getString(key: String) :String{
      return  getStringForDefault(key,"")
    }

    fun getStringForDefault(key: String,default: String):String{
        return get(key,default) as String
    }

    /**
     * 移除
     *
     * @param key key
     */
    fun remove(key: String?) {
        mmkv.remove(key)
    }
}